#!/usr/bin/env python
#   vim: fileencoding=utf-8

# This file is part of open-hea.
#
# open-hea is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# open-hea is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with open-hea.  If not, see <http://www.gnu.org/licenses/>.

__doc__ = """
Helper classes for test fixtures.

"""

import unittest

from openhea.model.unstableschema import metadata
from openhea.utils import SqliteAdapter

import sqlalchemy
from sqlalchemy.orm import sessionmaker

TestSession = sessionmaker()


class EmptySQLiteFixture(unittest.TestCase):
    """
    Sets up an empty SQLite database and binds it through
    SQLAlchemy to this module's TestSession class.
    """

    requires = [SqliteAdapter.BASE]

    @staticmethod
    def sqlite_fk_pragma(dbapi_con, con_record):
        dbapi_con.execute("pragma foreign_keys=ON")

    @staticmethod
    def on_connect(dbapi_con, con_record):
        EmptySQLiteFixture.sqlite_fk_pragma(dbapi_con, con_record)

    def setUp(self):
        adapter = SqliteAdapter()
        sqliteModule = adapter.discover(self.requires)
        if sqliteModule is None:
            self.skipTest(". ".join(adapter.diagnosis(self.requires)))
        self.engine = sqlalchemy.create_engine(
            "sqlite:///:memory:", module=sqliteModule)
        sqlalchemy.event.listen(self.engine, "connect", self.on_connect)
        metadata.bind = self.engine
        metadata.create_all()
        TestSession.configure(bind=self.engine)


class EmptySpacialiteFixture(EmptySQLiteFixture):
    """
    Sets up an empty Spacialite database and binds it through
    SQLAlchemy to this module's TestSession class.
    """

    requires = [SqliteAdapter.FK, SqliteAdapter.GEO]

    @staticmethod
    def on_connect(dbapi_con, con_record):
        SqliteAdapter.spacialite_load_extensions(dbapi_con)
        SqliteAdapter.spacialite_init(dbapi_con)
        EmptySQLiteFixture.sqlite_fk_pragma(dbapi_con, con_record)
